<template>
    <div class="manage-container">
        <!-- 页面标题和操作 -->
        <div class="page-header">
            <h2>帖子全量管理</h2>
            <div class="header-actions">
                <el-input
                        v-model="keyword"
                        placeholder="请输入关键词（标题/内容）"
                        clearable
                        style="width: 260px;"
                        @keyup.enter.native="handleSearch"
                />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
                <el-button
                        type="danger"
                        :disabled="selectedRows.length === 0"
                        :loading="batchLoading"
                        @click="batchDelete"
                >
                    批量删除 ({{ selectedRows.length }})
                </el-button>
                <el-button @click="refreshData">刷新</el-button>
            </div>
        </div>

        <!-- 数据表格 -->
        <el-table
                :data="tableData"
                v-loading="loading"
                @selection-change="onSelectionChange"
                stripe
                border
                style="width: 100%"
        >
            <el-table-column type="selection" width="50"/>

            <el-table-column prop="postId" label="帖子id" width="70"/>
            <el-table-column prop="userId" label="用户id" width="70"/>
            <el-table-column prop="gameId" label="游戏id" width="70"/>

            <el-table-column prop="title" label="标题" min-width="220" show-overflow-tooltip/>
            <el-table-column prop="content" label="内容" min-width="280" show-overflow-tooltip/>

            <el-table-column prop="likeCount" label="点赞数" width="70"/>
            <el-table-column prop="commentCount" label="评论数" width="80"/>
            <el-table-column prop="collectCount" label="收藏数" width="80"/>
            <el-table-column prop="status" label="审核状态" width="90"/>

            <!-- 精华状态（is_essence: 0 否 / 1 是） -->
            <el-table-column label="精华状态" width="100" align="center">
                <template #default="{ row }">
                    <el-switch
                            :model-value="getEssence(row)"
                            :active-value="1"
                            :inactive-value="0"
                            :disabled="row.status !== 1"
                            @change="val => onToggleEssence(row, val)"
                    />
                </template>
            </el-table-column>

            <!-- 操作列：单条删除 -->
            <el-table-column label="操作" width="100" align="center">
                <template #default="{ row }">
                    <el-button size="small" type="danger" @click="deleteOne(row)">删除</el-button>
                </template>
            </el-table-column>


        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="onSizeChange"
                    @current-change="onPageChange"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue'
import axios from '@/utils/axios'
import {ElMessage, ElMessageBox} from 'element-plus'

// 列表与分页状态
const loading = ref(false)
const batchLoading = ref(false)
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])

const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索关键字
const keyword = ref('')

const API_BASE = '/posts'

// 获取数据（支持搜索）
const fetchList = async () => {
    try {
        loading.value = true
        const kw = (keyword.value || '').trim()
        // 有关键词走敏感词模糊搜索；否则走全量分页
        const endpoint = kw ? 'searchSensitive' : 'page'
        const params: any = {
            page: currentPage.value,
            limit: pageSize.value
        }
        if (kw) params.keyword = kw

        const res = await axios.get(`${API_BASE}/${endpoint}`, {params})
        if (res.code === 200) {
            const data = res.data
            if (Array.isArray(data)) {
                tableData.value = data
                // 如果后端未返回 total，这里做最小兜底
                total.value = (currentPage.value - 1) * pageSize.value + data.length
            } else {
                // 兼容 IPage 结构
                tableData.value = data.records || data.rows || []
                total.value = data.total ?? data.count ?? tableData.value.length
                if (data.current) currentPage.value = data.current
                if (data.page) currentPage.value = data.page
                if (data.size) pageSize.value = data.size
                if (data.limit) pageSize.value = data.limit
            }
        } else {
            ElMessage.error(res.msg || '获取数据失败')
        }
    } catch (e) {
        console.error('获取列表失败:', e)
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}
// 单条删除（后端要求 status==-1 才可删）
const deleteOne = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要删除该帖子吗？', '删除确认', {type: 'warning', center: true})
        const res = await axios.post(`${API_BASE}/delete`, null, {params: {id: row.postId, status: row.status}})
        if (res.code === 200) {
            ElMessage.success('删除成功')
            fetchList()
        } else {
            ElMessage.error(res.msg || '删除失败')
        }
    } catch (e) {
        // 取消不提示
    }
}

// 批量删除：调用后端批量删除接口 /posts/batchDelete?ids=1&ids=2
const batchDelete = async () => {
    if (selectedRows.value.length === 0) return
    try {
        await ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条记录吗？`, '批量删除确认', {
            type: 'warning',
            center: true
        })
        batchLoading.value = true
        const ids = selectedRows.value.map(row => row.postId)
        const res = await axios.post(`${API_BASE}/batchDelete?${ids.map(id => `ids=${id}`).join('&')}`)
        if (res.code === 200) {
            ElMessage.success('批量删除成功')
        } else {
            ElMessage.error(res.msg || '批量删除失败')
        }
        selectedRows.value = []
        fetchList()
    } catch (e) {
        // 用户取消或部分失败
    } finally {
        batchLoading.value = false
    }
}


// 事件与工具函数
const onSelectionChange = (rows: any[]) => {// 选中行变化时更新状态
    selectedRows.value = rows
}
const onSizeChange = (val: number) => {// 每页条数变化时更新状态
    pageSize.value = val;
    currentPage.value = 1;
    fetchList()
}
const onPageChange = (val: number) => {// 页码变化时更新状态
    currentPage.value = val;
    fetchList()
}
const handleSearch = () => {// 搜索按钮点击时触发搜索
    currentPage.value = 1;
    fetchList()
}
const resetSearch = () => {// 重置搜索条件
    keyword.value = '';
    currentPage.value = 1;
    fetchList()
}
const refreshData = () => fetchList()// 刷新数据


// 读取行数据中的精华值（兼容 isEssence / is_essence）
const getEssence = (row: any) => {
    if (typeof row.isEssence !== 'undefined') return row.isEssence
    if (typeof row.is_essence !== 'undefined') return row.is_essence
    return 0
}

// 切换精华状态
const onToggleEssence = async (row: any, val: number) => {
    // 仅审核通过(status==1)的帖子允许设置精华
    if (row.status !== 1) {
        ElMessage.warning('仅审核通过的帖子可设置精华')
        return
    }
    try {
        const res = await axios.post(`${API_BASE}/update`, {postId: row.postId, isEssence: val})
        if (res.code === 200) {
            ElMessage.success('精华状态已更新')
            // 本地同步
            if (typeof row.isEssence !== 'undefined') row.isEssence = val
            if (typeof row.is_essence !== 'undefined') row.is_essence = val
        } else {
            ElMessage.error(res.msg || '更新失败')
        }
    } catch (e) {
        ElMessage.error('更新失败')
    }
}

// 组件挂载时初始化数据
onMounted(() => {
    fetchList()
})
</script>

<style scoped>
.manage-container {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e6e6e6;
}

.page-header h2 {
    margin: 0;
    color: #303133;
}

.header-actions {
    display: flex;
    gap: 10px;
    align-items: center;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

:deep(.el-table .cell) {
    word-break: break-word;
}
</style>

<!-- 全局样式：强制 Element Plus MessageBox 居中显示 -->
<style>
.el-message-box__wrapper {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    margin: 0 !important;
    z-index: 9999 !important;
}

.el-message-box {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    margin: 0 !important;
    z-index: 10000 !important;
    /* 背景与文字颜色 */
    background: #ffffff !important;
    color: #303133 !important;
    border: 1px solid #dcdfe6 !important;
    border-radius: 8px !important;
    box-shadow: 0 12px 28px rgba(0, 0, 0, 0.22) !important;
    /* 提升整体尺寸 */
    width: 520px !important;
    max-width: 90vw !important;
    padding: 18px 22px !important;
}

/* 标题与正文使用深色文字，保证可读性 */
.el-message-box__title,
.el-message-box__message,
.el-message-box__content {
    color: #303133 !important;
    text-align: center !important;
}

/* 底部按钮区域轻微留白 */
.el-message-box__btns {
    padding-top: 8px !important;
    display: flex !important;
    justify-content: center !important;
}

/* 放大标题与正文字号、行高，增强可读性 */
.el-message-box__title {
    font-size: 18px !important;
    line-height: 24px !important;
    width: 100% !important;
    text-align: center !important;
}

.el-message-box__message,
.el-message-box__content {
    font-size: 15px !important;
    line-height: 22px !important;
    text-align: center !important;
}

/* 放大按钮内边距，避免拥挤 */
.el-message-box__btns .el-button {
    padding: 10px 16px !important;
}

/* 关闭按钮固定在右上角 */
.el-message-box__headerbtn {
    position: absolute !important;
    top: 10px !important;
    right: 10px !important;
}
</style>
